import { getUserInfo, login } from '@/api'
import router from '@/router'
import type { LoginInfo, MenuType } from '@/types'
import { localCache } from '@/utils/cache'
import { ElMessage } from 'element-plus'
import { defineStore } from 'pinia'

interface LoginState {
  token: string
  userInfo: any
  menus: MenuType[]
}

const useLoginStore = defineStore('login', {
  state: (): LoginState => ({
    token: localCache.get('token') ?? '',
    userInfo: localCache.get('userInfo') ?? '{}',
    menus: localCache.get('menus') ?? []
  }),

  actions: {
    async handleLoginAction(account: LoginInfo) {
      const token = await login(account)

      localCache.set('token', token)

      const { userName, menus } = await getUserInfo()

      this.userInfo = { userName }
      localCache.set('userInfo', { userName })
      this.menus = menus
      localCache.set('menus', menus)

      router.push('/')
      ElMessage.success('登录成功')
    }
  }
})

export default useLoginStore
